<?php
namespace Admin\Controller;
use Admin\Model\LoginModel;
use Admin\Model\UserModel;
use Frame\Libs\BaseController;

class LoginController extends BaseController {
    private $model;
    private $userModel;
    
    public function __construct() {
        parent::__construct();
        $this->model = new LoginModel();
        $this->userModel = new UserModel();
    }
    
    // 获取客户端IP地址的方法
    private function getClientIP() {
        if (getenv('HTTP_CLIENT_IP')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } else if (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } else if (getenv('REMOTE_ADDR')) {
            $ip = getenv('REMOTE_ADDR');
        } else {
            $ip = 'unknown';
        }
        return $ip;
    }
    
    public function login() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->smarty->display('index/login.tpl');
            return;
        }
        
        //清洗数据,去掉空格等字符
        $username = isset($_POST['username']) ? trim($_POST['username']) : '';
        $password = isset($_POST['password']) ? trim($_POST['password']) : '';
        $remember = isset($_POST['remember']) ? 1 : 0;
        
        // 简单的服务器端验证
        if (empty($username) || empty($password)) {
            echo json_encode(array('success' => false, 'message' => '用户名和密码不能为空'));
            exit;
        }
        
        // 调用模型进行验证
        $result = $this->model->verify($username, $password);
        
        if ($result) {
            // 登录成功，设置会话
            session_start();
            $_SESSION['admin_user'] = $username;
            
            // 获取客户端IP并更新用户登录信息
            $ip = $this->getClientIP();
            $this->userModel->updateUserLoginInfo($username, $ip);
            
            // 如果选择了记住我，可以设置cookie
            if ($remember) {
                // 这里可以添加记住我的逻辑
            }
            
            // 返回成功响应给前端
            echo json_encode(array('success' => true, 'message' => '登录成功，正在跳转...'));
        } else {
            // 登录失败
            echo json_encode(array('success' => false, 'message' => '用户名或密码错误'));
        }
        exit;
    }
    
    // 退出登录
    public function logout() {
        session_start();
        session_destroy();
        $this->redirect('admin.php?c=Login&a=login');
    }
}